<!DOCTYPE HTML>
<html>
<head>
    <!-- twitter bootstrap CSS stylesheet - included to make things pretty, not needed or used by cornerstone -->
    <link href="../bootstrap.min.css" rel="stylesheet">

    <link href="../cornerstone.min.css" rel="stylesheet">

</head>
<body>
<div class="container">
    <div class="page-header">
        <h1>Example of displaying a WADO-RS RetreiveFrame response using Cornerstone</h1>
        <p class="lead">
            Enter a WADO-RS URL to a SOP Instance.
        </p>
    </div>

    <div id="loadProgress">Image Load Progress:</div>

    <div class="row">
        <form id="form" class="form-horizontal">
            <div class="form-group">
                <label class="control-label col-sm-1" for="apikey">APIKEY</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" id="apikey" placeholder="APIKEY" value="">
                </div>
             </div>
             <div class="form-group">
                <label class="control-label col-sm-1" for="wadoURL">URL</label>
                <div class="col-sm-8">
                    https://api.hackathon.siim.org/dicomweb/studies/1.3.6.1.4.1.14519.5.2.1.7777.9002.198875685720513246512710453733/series/1.3.6.1.4.1.14519.5.2.1.7777.9002.207203214132667549392101803048/instances/1.3.6.1.4.1.14519.5.2.1.7777.9002.327873213718058651550666129029/frames/1
                    <input class="form-control" type="text" id="wadoURL" placeholder="Enter WADO URL" value="https://raw.githubusercontent.com/cornerstonejs/cornerstoneWADOImageLoader/master/testImages/wadors">
                </div>
             </div>
            <div class="form-group">
                <div class="col-sm-3">
                    <button class="form-control" type="button" id="downloadAndView" class="btn btn-primary">Download and View</button>
                </div>
            </div>
        </form>
    </div>

    <div style="width:512px;height:512px;position:relative;color: white;display:inline-block;border-style:solid;border-color:black;"
         oncontextmenu="return false"
         class='disable-selection noIbar'
         unselectable='on'
         onselectstart='return false;'
         onmousedown='return false;'>
        <div id="dicomImage"
             style="width:512px;height:512px;top:0px;left:0px; position:absolute">
        </div>
    </div>
</div>
</body>

<!-- include the cornerstone library -->
<script src="../cornerstone.min.js"></script>
<SCRIPT src="../cornerstoneMath.min.js"></SCRIPT>
<SCRIPT src="../cornerstoneTools.min.js"></SCRIPT>

<!-- include the dicomParser library as the WADO image loader depends on it -->
<script src="../dicomParser.min.js"></script>

<!-- include the cornerstoneWADOImageLoader library -->
<script src="../../dist/cornerstoneWADOImageLoader.js"></script>

<!-- Lines ONLY required for this example to run without building the project -->
<script>window.cornerstoneWADOImageLoader || document.write('<script src="https://unpkg.com/cornerstone-wado-image-loader">\x3C/script>')</script>
<script src="../utils/initializeWebWorkers.js"></script>

<script>
    cornerstoneWADOImageLoader.external.cornerstone = cornerstone;

    cornerstoneWADOImageLoader.configure({
        beforeSend: function(xhr) {
            // Add custom headers here (e.g. auth tokens)
            const apiKey = document.getElementById('apikey').value;
            if(apiKey && apiKey.length) {
                xhr.setRequestHeader('APIKEY', apiKey);
            }
        }
    });


    let loaded = false;

    function loadAndViewImage(imageId) {
        const element = document.getElementById('dicomImage');
        //try {
        cornerstone.loadImage(imageId).then(function(image) {
            console.log(image);
            const viewport = cornerstone.getDefaultViewportForImage(element, image);
            cornerstone.displayImage(element, image, viewport);
            if(loaded === false) {
                cornerstoneTools.mouseInput.enable(element);
                cornerstoneTools.mouseWheelInput.enable(element);
                cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
                cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
                cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
                cornerstoneTools.zoomWheel.activate(element); // zoom is the default tool for middle mouse wheel
                loaded = true;
            }
        }, function(err) {
            alert(err);
        });
        /*}
         catch(err) {
         alert(err);
         }*/
    }

    function getImageFrameURI(metadataURI, metadata) {
        // Use the BulkDataURI if present int the metadata
        if(metadata["7FE00010"] && metadata["7FE00010"].BulkDataURI) {
            return metadata["7FE00010"].BulkDataURI
        }

        // fall back to using frame #1
        return metadataURI + '/frames/1';
    }


    function downloadAndView() {
        const url = document.getElementById('wadoURL').value;
        const metadataURI = url + "/metadata";

        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                // Make sure it's a JSON document
                data = JSON.parse(this.responseText);

                console.log(data);

                const metadata = data[0];
                const imageFrameURI = getImageFrameURI(metadataURI, metadata);
                const imageId = 'wadors:' + imageFrameURI;

                cornerstoneWADOImageLoader.wadors.metaDataManager.add(imageId, metadata);

                // image enable the dicomImage element and activate a few tools
                loadAndViewImage(imageId);
            }
        };

        xhr.open("GET", metadataURI, true);
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.send();
    }

    cornerstone.events.addEventListener('cornerstoneimageloadprogress', function(event) {
        const eventData = event.detail;
        const loadProgress = document.getElementById('loadProgress');
        loadProgress.textContent = `Image Load Progress: ${eventData.percentComplete}%`;
    });


    const element = document.getElementById('dicomImage');
    cornerstone.enable(element);

    document.getElementById('downloadAndView').addEventListener('click', function() {
        downloadAndView();
    });

    const form = document.getElementById('form');
    form.addEventListener('submit', function() {
        downloadAndView();
        return false;
    });
</script>
</html>
